var app = angular.module('fiveApp', ['oc.lazyLoad', 'ui.router', 'fiveApp.controllers', 'fiveApp.directives', 'fiveApp.services', 'fiveApp.filters']);
var now_time = new Date().getTime();
app.config(['$stateProvider', '$urlRouterProvider',
    function ($stateProvider, $urlRouterProvider) {
        $stateProvider
            .state('template', {
                url: '/:controller/:action/:query',
                templateUrl: function (e) {
                    return '/static/index/tpl/' + e.controller + '/' + e.action + '.html?time=' + now_time;
                },
                resolve: loadJs()
            });
        var hash = sessionStorage.getItem('hash');

        var defaultUrl = '/index/index/';
        if (window._defaultUrl) defaultUrl = window._defaultUrl
        if (hash) {
            defaultUrl = hash;
            sessionStorage.setItem('hash', '');
        }
        var search = window.location.search;
        $urlRouterProvider.otherwise(defaultUrl);
    }
])


app.run(['$rootScope', '$state', '$location', '$timeout',
    function ($rootScope, $state, $location, $timeout) {

        //tab access_key
        $rootScope.location = function (path, tab) {
            $timeout(function () {
                if (tab) {
                    var exist = $rootScope.TabMenu.some(function (item) {
                        return item.access == tab;
                    })
                    var access = window._access[tab] || '';
                    if (access && !exist) {
                        $rootScope.TabMenu.push({name: access['name'], url: path, access: tab});
                    }
                    $rootScope.ActiveTabMenu = tab || '';
                    $rootScope.menuStatus();
                }
                $location.path(path);
            }, 100);
        }

        $rootScope.$on('$stateChangeStart', function () {

        });
        $rootScope.$on('$stateChangeSuccess', function () {
            document.documentElement.scrollTop = 0;
        })

    }
])

var loadJs = function () {
    return {
        load: ['$ocLazyLoad', '$stateParams', function ($ocLazyLoad, $stateParams) {
            var params = $stateParams;
            var filePath = ['/static/index/js/controller/' + params.controller + '.js?time=' + now_time];
            var extras = (params.controller + '/' + params.action).toLocaleLowerCase();
            if (actionExtraJs[extras]) {
                actionExtraJs[extras].forEach(function (v) {
                    var extra = JS_MAP[v];
                    if (angular.isArray(extra)) {
                        extra.forEach(function (e) {
                            filePath.push(e);
                        })
                    } else {
                        filePath.push(extra);
                    }
                })
            }
            return $ocLazyLoad.load({
                files: filePath
            })
        }]
    };
}

var actionExtraJs = {

};

var JS_MAP = {

};